package com.zh.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.zh.constants.Constants;
import com.zh.pojo.bo.PayOrderBo;
import com.zh.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.support.RocketMQConsumerLifecycleListener;
import org.apache.rocketmq.spring.support.RocketMQListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 支付订单的消费者
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = Constants.MQ.CONSUMER_GROUP_PAY_ORDER,
        topic = Constants.MQ.TOPIC_PAY_ORDER,
        selectorExpression = Constants.MQ.TAGS_PAY_ORDER,
        messageModel = MessageModel.CLUSTERING
)
public class PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 保存支付单
        byte[] body = messageExt.getBody();
        // 获取消息
        String msg = new String(body, StandardCharsets.UTF_8);
        // 通过JSON 反序列化 转成对象
        PayOrderBo payOrderBo = JSON.parseObject(msg, PayOrderBo.class);
        //  开始处理支付单  保存支付单
        payOrderService.create(payOrderBo);
        log.info("创建订单 message: {}", payOrderBo);
    }
}
